﻿namespace Leetcode.N0424.V1;
public class Solution
{
    public int CharacterReplacement(string s, int k)
    {
        int diffLetterCount = 0;
        int[] eachLetterCount = new int[26];
        int maxLength = 0;
        int indexTo = 0;
        int indexFrom = 0;

        while (true)
        {
            while (indexTo < s.Length)
            {
                if (s[indexTo] != s[indexFrom])
                {
                    if (diffLetterCount == k)
                    {
                        break;
                    }
                    else
                    {
                        diffLetterCount++;
                    }
                }

                eachLetterCount[s[indexTo] - 'A']++;
                indexTo++;
            }

            if (indexFrom >= s.Length)
            {
                return maxLength;
            }

            if (diffLetterCount < k)
            {
                return Math.Max(maxLength, Math.Min(eachLetterCount[s[indexFrom] - 'A'] + k, s.Length));
            }

            maxLength = Math.Max(maxLength, eachLetterCount[s[indexFrom] - 'A'] + diffLetterCount);

            while (diffLetterCount >= k && indexFrom < indexTo)
            {
                eachLetterCount[s[indexFrom] - 'A']--;

                if (indexFrom < indexTo - 1 && s[indexFrom] != s[indexFrom + 1])
                {
                    diffLetterCount = diffLetterCount - eachLetterCount[s[indexFrom + 1] - 'A'] + eachLetterCount[s[indexFrom] - 'A'];
                }
                indexFrom++;
            }

        }
    }
}
